package net.easyjava.test.aws;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxnacy on 16/11/23.
 */
public class S3Demo {
    public static final String BUCKET_EASYJAVA_TEST = "easyjava-test";
    public static final String BUCKET_EASYJAVA_TEST1 = "easyjava-test1";

    public static final String PATH1 = "/Users/wxnacy/Documents/图片/1111.jpg";
    private static AWSCredentials credentials;
    private static AmazonS3 s3client;

    public S3Demo() {
        init();
    }

    public static void main(String[] args) {
        init();
        try {
            //创建bucket
//          createBucket();
            //上传文件到存储桶
            putObject();
            //获取对象
//            getObject();
            //列出对象key
//            ListKey();
            //删除对象
//            delteObject();

        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which " +
                    "means your request made it " +
                    "to Amazon S3, but was rejected with an error response" +
                    " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which " +
                    "means the client encountered " +
                    "an internal error while trying to " +
                    "communicate with S3, " +
                    "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }

    }

    private static void init() {
        try {
            credentials = new BasicAWSCredentials(AWSConstants.KEY_ID, AWSConstants.KEY_SECRET);
            s3client = new AmazonS3Client(credentials);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建bucket
     */
    private static void createBucket() {
        s3client.setRegion(Region.getRegion(Regions.US_WEST_1));

        if (!(s3client.doesBucketExist(BUCKET_EASYJAVA_TEST1))) {
            s3client.createBucket(new CreateBucketRequest(
                    BUCKET_EASYJAVA_TEST1));
        }
        // Get location.
        String bucketLocation = s3client.getBucketLocation(new GetBucketLocationRequest(BUCKET_EASYJAVA_TEST1));
        System.out.println("bucket location = " + bucketLocation);

    }


    /**
     * 上传文件到存储桶
     */
    private static S3Obj putObject() {
        File file = new File(PATH1);
        String key = "test/" + System.currentTimeMillis();
        PutObjectResult por = s3client.putObject(new PutObjectRequest(BUCKET_EASYJAVA_TEST, key, file));

        System.out.println("por.getVersionId() = " + por.getVersionId());
        System.out.println("por.getContentMd5() = " + por.getContentMd5());
        //设置 versionID
        BucketVersioningConfiguration config = new BucketVersioningConfiguration()
                .withStatus(BucketVersioningConfiguration.ENABLED);
        SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest = new SetBucketVersioningConfigurationRequest(
                BUCKET_EASYJAVA_TEST, config);
        s3client.setBucketVersioningConfiguration(setBucketVersioningConfigurationRequest);

        //上传带有versionID的文件
        String content = "hello aws";
        key = "test/" + System.currentTimeMillis();
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader("Subject", "Content-As-Object");
//        metadata.setHeader("Content-Length", content.length());
        PutObjectRequest request = new PutObjectRequest(BUCKET_EASYJAVA_TEST, "test/" + System.currentTimeMillis(),
                new ByteArrayInputStream(content.getBytes()), metadata)
                .withCannedAcl(CannedAccessControlList.AuthenticatedRead);
        PutObjectResult response = s3client.putObject(request);
        System.out.println("response.getVersionId() = " + response.getVersionId());


        return new S3Obj(response.getVersionId(), key);
    }


    public String putObject(String key) {
        File file = new File(PATH1);
        PutObjectResult por = s3client.putObject(new PutObjectRequest(BUCKET_EASYJAVA_TEST, key, new ByteArrayInputStream("test".getBytes()),new ObjectMetadata()));
        return key;
    }

    /**
     * 获取对象
     *
     * @throws IOException
     */
    private static void getObject() throws IOException {
        S3Object object = s3client.getObject(new GetObjectRequest(BUCKET_EASYJAVA_TEST, "test/1111.jpg"));

        S3ObjectInputStream is = object.getObjectContent();
        byte[] bytes = new byte[10];
        is.read(bytes);

        System.out.println("new String(bytes) = " + new String(bytes));

        is.close();

    }

    /**
     * 列出bucket中的key
     */
    private static void ListKey() {
        System.out.println("Listing objects");
        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(BUCKET_EASYJAVA_TEST).withMaxKeys(10);
        ListObjectsV2Result result;
        do {
            result = s3client.listObjectsV2(req);

            for (S3ObjectSummary objectSummary :
                    result.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + "  " +
                        "(size = " + objectSummary.getSize() +
                        ")");
            }
            System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
            req.setContinuationToken(result.getNextContinuationToken());
        } while (result.isTruncated() == true);
    }


    /**
     * 删除对象
     */
    private static void delteObject() {
        //待遇versionID的删除
        s3client.deleteVersion(new DeleteVersionRequest(BUCKET_EASYJAVA_TEST, "test/1479890552435", ".u51qcgJm8LhLM3XzRgHfZh8cJOPT0C."));
        //不用versionID删除
        s3client.deleteObject(new DeleteObjectRequest(BUCKET_EASYJAVA_TEST, "test/1479890639271"));

        //批量删除
        DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(BUCKET_EASYJAVA_TEST);

        List<DeleteObjectsRequest.KeyVersion> keys = new ArrayList<DeleteObjectsRequest.KeyVersion>();
        keys.add(new DeleteObjectsRequest.KeyVersion(putObject().key));
        multiObjectDeleteRequest.setKeys(keys);

        DeleteObjectsResult delObjRes = s3client.deleteObjects(multiObjectDeleteRequest);
        System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size());


    }


    /**
     * 对象
     */
    private static class S3Obj {
        private String versionId;
        private String key;

        public S3Obj(String versionId, String key) {
            this.versionId = versionId;
            this.key = key;
        }

        public String getVersionId() {
            return versionId;
        }

        public void setVersionId(String versionId) {
            this.versionId = versionId;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }
    }


}
